package com.bbjob.service.impl;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.bbjob.client.result.ResultForDeliveryUserInfo;
import com.bbjob.dto.Result;
import com.bbjob.entity.JwtUser;
import com.bbjob.mapper.DeliveryUserMapper;
import com.bbjob.model.DeliveryUser;
import com.bbjob.model.User;
import com.bbjob.service.ISystemService;
import com.bbjob.toolutil.HttpClientUtil;
import com.bbjob.toolutil.Tool;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

@Service
public class UserServiceImpl implements UserDetailsService {
	
	@Value("${sys.uniquecode}")
	private String uniquecode;
	@Value("${examol.center.url}")
	private String centerUrl;
	@Value("${examol.center.delivery.login}")
	private String centerDeliveryLoginUrl;
	@Resource
	private ISystemService systemService;
	@Resource
	private DeliveryUserMapper deliveryUserMapper;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uniquecode", uniquecode);
		
		User user = new User();
		
		try {
			Result testConn = systemService.TestConn();
			if (testConn.getCode() == 200) {
				params.put("username", username);
				
				String resultStr = HttpClientUtil.doPost(centerUrl + centerDeliveryLoginUrl, params);
				GsonBuilder builder = new GsonBuilder();
			    
				builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { 
					@Override   
					public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
						return new Date(json.getAsJsonPrimitive().getAsLong()); 
					}
				});
				
				ResultForDeliveryUserInfo result = builder.create().fromJson(resultStr, ResultForDeliveryUserInfo.class);
				
				if (result.getCode() == 200) {
					if (result.getData() != null) {
						User cUser = result.getData();
						DeliveryUser dUser = new DeliveryUser();
						dUser.setUsername(cUser.getUsername());
						dUser.setRealname(cUser.getRealname());
						dUser.setEmail(cUser.getEmail());
						dUser.setPhone(cUser.getPhone());
						dUser.setPassword(cUser.getPassword());
						dUser.setCreateTime(cUser.getCreateTime());
						dUser.setOrganId(cUser.getOrganId());
						dUser.setType(dUser.getType());
						dUser.setEnable(dUser.getEnable());
						dUser.setFree1(cUser.getFree1());
						dUser.setFree2(cUser.getId());
						dUser.setFree3(cUser.getFree3());
						List<DeliveryUser> list = deliveryUserMapper.selectByParams(dUser);
						
						if (list.size() > 0) {
							dUser.setId(list.get(0).getId());
							deliveryUserMapper.updateByPrimaryKey(dUser);
						} else {
							dUser.setId(Tool.getUUID());
							dUser.setFree2(cUser.getId());
							deliveryUserMapper.insert(dUser);
						}
						List<SimpleGrantedAuthority> authorities=null;
						authorities=new ArrayList<SimpleGrantedAuthority>();
						authorities.add(new SimpleGrantedAuthority("-1"));
						return new JwtUser(result.getData(), authorities);
					} else {
						throw new UsernameNotFoundException("未查询到用户信息");
					}
				} else {
					throw new UsernameNotFoundException("查询用户信息失败");
				}
			} else {
				DeliveryUser dUser = new DeliveryUser();
				dUser.setUsername(username);
				List<DeliveryUser> list = deliveryUserMapper.selectByParams(dUser);
				if (list.size() > 0) {
					dUser = list.get(0);
					user.setUsername(dUser.getUsername());
					user.setRealname(dUser.getRealname());
					user.setEmail(dUser.getEmail());
					user.setPhone(dUser.getPhone());
					user.setPassword(dUser.getPassword());
					user.setCreateTime(dUser.getCreateTime());
					user.setOrganId(dUser.getOrganId());
					user.setType(dUser.getType());
					user.setEnable(dUser.getEnable());
					user.setFree1(dUser.getFree1());
					user.setFree2(dUser.getFree2());
					user.setFree3(dUser.getFree3());
					user.setId(dUser.getFree2());
					
					List<SimpleGrantedAuthority> authorities=null;
					authorities=new ArrayList<SimpleGrantedAuthority>();
					authorities.add(new SimpleGrantedAuthority("-1"));
					
					return new JwtUser(user, authorities);
				} else {
					
					throw new UsernameNotFoundException("未查询到用户信息");
				}
			}
			
		} catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
	}


}